package com.zhangtao.demo.aop.logAspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.zhangtao.demo.common.util.ThrowableUtil;
import org.springframework.web.multipart.MultipartFile;

/**
 *
 * @ClassName: LogAspect.java
 * @Description: controller日志记录切面
 * @author 张涛
 * @version V1.0
 * @Date 2018年10月19日 上午11:18:01
 */
@Aspect
@Component
public class LogAspect {
	private static final String LOGASPECT = "[LogAspect]";
	private static final Logger LOGGER = LoggerFactory.getLogger(LogAspect.class);

	@Pointcut("execution(public * com.zhangtao.demo.controller.*.*(..))")
	public void logAdvice() {
	}

	@Before(value = "logAdvice()")
	public void doBefore(JoinPoint joinPoint) throws Throwable {
		Object[] args = joinPoint.getArgs();
		StringBuffer paramStr = new StringBuffer();
		if (args != null && args.length > 0) {
			for (Object obj : args) {
				if (!(obj instanceof MultipartFile)) {
					try {
						paramStr.append(JSONObject.toJSONString(obj)).append(",");
					} catch (Exception e) {
						LOGGER.error("get args failed : {}", ThrowableUtil.getErrorInfoFromThrowable(e));
					}
				}
			}
		}
		LOGGER.info("{} -- request info : {}, param : {}", LOGASPECT, joinPoint.toString(), paramStr);
	}

	@AfterReturning(returning = "ret", pointcut = "logAdvice()")
	public void doAfter(Object ret) throws Throwable {
		String resJson = null;
		if (ret != null) {
			try {
				resJson = JSONObject.toJSONString(ret);
			} catch (Exception e) {
				LOGGER.error("parse ret failed : {}", ThrowableUtil.getErrorInfoFromThrowable(e));
			}
		}
		LOGGER.info("{} -- response info : {}", LOGASPECT, resJson);
	}

}
